# 作业2：
#     1、写一个函数，入参是qq群号码，然后把这个群里面所有人的头像，在当前目录创建一个qq群号码的文件夹，把头像下载到这个文件夹里面,
#     头像文件名以群备注为名称,现场-万术成.jpg,如果这个人没有群备注，那么使用昵称做名称
#
#     https://qun.qq.com/
#     https://q4.qlogo.cn/g?b=qq&nk=475566024&s=140
import requests
import os
import traceback
import string
#cookie="RK=BcAleFD/d8; ptcz=49ff0680d48e90619521ee664286a57360052592649b54ab0162e912e3cac58a; p_uin=o0925182968; traceid=db32db5145; uin=o0925182968; pgv_pvid=2768259257; pgv_info=ssid=s2230178250; skey=@hfA1S458g; pt4_token=Y-vzaF8Fl9YQOy0Wf02rNLz1eKigCgIG62rd9FWTCZ8_; p_skey=VfXgh*EQz2kNvDzMO3jbGlGTWk-pflqLNg9IkPVdal0_"
def qq_image(qq_number):
    file_path = os.path.split(os.path.realpath(__file__))[0]#查询当前脚本的路径
    # 判断当前目录是否有群号命名的文件夹
    s=os.path.exists(qq_number)
    print(s)
    print(os.getcwd())
    if os.path.exists(qq_number):
        print(os.getcwd())# 切换到当前目录
    else:
        os.chdir("%s" % file_path)
        os.mkdir("%s" % qq_number)


    #通过接口获取该群共有多少群成员
    url = "https://qun.qq.com/cgi-bin/qun_mgr/search_group_members?"
    payload = {'gc':qq_number ,'st': '0','end': '20','sort': '0','bkn': '808234933'}
    headers = {'Cookie': 'RK=BcAleFD/d8; ptcz=49ff0680d48e90619521ee664286a57360052592649b54ab0162e912e3cac58a; p_uin=o0925182968; traceid=db32db5145; uin=o0925182968; pgv_pvid=2768259257; pgv_info=ssid=s2230178250; skey=@XBAhQpe0W; pt4_token=WE7Tutjh4*l98RKMoeju4hHLOnlj5mqhcAa0e4f3Zd0_; p_skey=Ly8ENaG06l1qUWYuUCcGQnKM8Sr24M*PfM5GfP8rigU_'}
    req = requests.request("POST", url, headers=headers, data=payload)
    try:
        qq_all=req.json()
        qq_number_total=qq_all["search_count"]

        #通过群成员数判断要循环多少次才能拿到所有到群成员信息
        if int(qq_number_total)/20>1:
            s=qq_number_total//20+1
        else:
            s=1
        k = 0
        for i in range(0,s):
            payload_list = {'gc': qq_number,
                           'st': k*20,
                           'end': k*20+19,
                           'sort': '0',
                           'bkn': '808234933'}
            req_new = requests.request("POST", url, headers=headers, data=payload_list)
            qq_all_l = req_new.json()
            qq_mems_list=qq_all_l["mems"]
            k=k+1
            #循环获取每页返回的列表每个群员到信息，并下载头像到当前目前的对应群号文件夹下
            for j in range(0,len(qq_mems_list)):
                card = qq_mems_list[j]["card"]
                nick = qq_mems_list[j]["nick"]
                uin = qq_mems_list[j]["uin"]
                url_image = "https://q4.qlogo.cn/g?b=qq&nk=%s &s=140" % uin
                eq_image = requests.get(url_image)
                full_path = os.path.join(file_path, str(qq_number))
                os.chdir("%s" % full_path)
                if card!="":
                    with open("%s.jpg"%card , 'wb') as fw:
                        fw.write(eq_image.content)
                else:
                    with open("%s.jpg"% nick , 'wb') as fw:
                        fw.write(eq_image.content)
                print(url_image,card,nick,uin)
    except Exception as e:
        print(e)
        traceback.print_exc()


if __name__ == "__main__":
    qq_image("31565139")
